﻿using System.Windows;
using System;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Input;

namespace Xcj.Mes.Core.CustomControls
{
    public class DataGridEx : DataGrid
    {
        public bool IsAutoScrollToEnd { get; set; } = true;

        private ScrollViewer Scroll { get; set; }

        public DataGridEx() : base()
        {
            RowHeight = 36;
            this.Loaded += OnLoaded;
        }

        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var grid = VisualTreeHelper.GetChild(this, 0);
                if (grid == null)
                    return;

                var scroll = VisualTreeHelper.GetChild(grid, 0);
                if (scroll == null)
                    return;

                this.Scroll = scroll as ScrollViewer;
                this.Scroll.ScrollChanged += AutoScrollToEnd;
                this.Scroll.GotMouseCapture += DisableAutoScrollToEnd;
                this.SelectionChanged += DisableAutoScrollToEnd;
                this.PreviewMouseWheel += DisableAutoScrollToEnd;
                this.KeyDown += EnableAutoScrollToEnd;
                this.MouseLeave += OnMouseLeave;
                this.IsAutoScrollToEnd = true;
            }
            catch { }
        }

        private void AutoScrollToEnd(object sender, ScrollChangedEventArgs e)
        {
            if (e.ExtentHeightChange > 0 && this.IsAutoScrollToEnd)
                (sender as ScrollViewer)?.ScrollToEnd();
        }

        private void EnableAutoScrollToEnd(object sender, System.Windows.Input.KeyEventArgs e)
        {
            //if (((e.Key == Key.Space) || (e.Key == Key.Enter)) && !this.IsAutoScrollToEnd)
            //{
            //    this.IsAutoScrollToEnd = true;
            //    this.Scroll?.ScrollToEnd();
            //}

            if (!this.IsAutoScrollToEnd)
                this.IsAutoScrollToEnd = true;
        }

        private void OnMouseLeave(object sender, MouseEventArgs e)
        {
            if (!this.IsAutoScrollToEnd)
                this.IsAutoScrollToEnd = true;
        }

        private void DisableAutoScrollToEnd(object sender, EventArgs e)
        {
            if (this.IsAutoScrollToEnd)
                this.IsAutoScrollToEnd = false;
        }

        private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            this.IsAutoScrollToEnd = true;
        }
    }
}
